import { _decorator } from 'cc';
const { ccclass, property } = _decorator;

@ccclass('LocalStorageMgr')
export class LocalStorageMgr {

    public static setItem(key: string, value: any): void {
        try {
            // console.log(`Setting item in localStorage: ${key} =`, value);
            localStorage.setItem(key, JSON.stringify(value));
        } catch (e) {
            // console.error(`Failed to save to local storage: ${key}`, e, value);
        }
    }

    public static getItem<T>(key: string): T | null {
        const value = localStorage.getItem(key);

        // 检查 value 是否为 null 或空字符串
        if (value === null || value === "undefined" || value === "") {
            // console.warn(`No valid item found in localStorage for key: ${key}`);
            return null;
        }

        try {
            const parsedValue = JSON.parse(value) as T;
            return parsedValue;
        } catch (e) {
            // console.warn(`Failed to parse local storage data: ${key}`, e, value);
            return null;
        }
    }


    public static hasItem(key: string): boolean {
        const exists = localStorage.getItem(key) != null;
        // console.log(`Checking existence of item in localStorage: ${key} = ${exists}`);
        return exists;
    }

    public static removeItem(key: string): void {
        try {
            // console.log(`Removing item from localStorage: ${key}`);
            localStorage.removeItem(key);
        } catch (e) {
            console.error(`Failed to remove from local storage: ${key}`, e);
        }
    }

    public static clear(): void {
        try {
            // console.log(`Clearing all items from localStorage`);
            localStorage.clear();
        } catch (e) {
            console.error(`Failed to clear local storage`, e);
        }
    }
}